/**
 * 文件下载
 * Created by mlr on 2016/9/6.
 */
var path = require('path')
    , fs = require('fs')
    , mime = require('mime')
    , config = require('config')
    , uploadConfig = config.get('SYS.upload');

exports = module.exports = function (req, res) {
    var data = req.query;
    var fileName = data.name;
    var _fileName = fileName.substring(0, fileName.lastIndexOf('.'));
    var appName = _fileName.split('_')[0];
    var filePath = path.join(uploadConfig.dirName, appName, fileName);
    if (!fs.existsSync(path.join(uploadConfig.dirName, appName))) {
        fs.mkdirSync(path.join(uploadConfig.dirName, appName));
    }
    module.sendWebFile(filePath, data.fileName, res);
};

module.sendSocketFile = function (file_path, res) {
    if (fs.existsSync(file_path)) {
        var rstream = fs.createReadStream(file_path);
        rstream.on('error', function (e) {
            console.log('---------error----', e);
        });
        var type = mime.lookup(file_path);
        res.set('Content-Type', type);
        rstream.pipe(res);
    } else {
        res.sendStatus(404);
    }
};

module.sendWebFile = function (file_path, filename, res) {
    try {
        res.download(file_path, filename, function (err) {
            if (err) {
                res.sendStatus(404);
            }
        });
    } catch(e) {
        res.sendStatus(404);
    }
};
